package com.wowoai.utils;

import cn.hutool.core.io.FileUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class FileUtils {

    /**
     * 切割图片
     *
     * @param fileImage
     * @param rows      组合图片矩阵的行
     * @param cols      组合图片矩阵的列
     * @return 切割后的图片文件集合
     * @throws IOException
     */
    public static List<File> splitImage(File fileImage, int rows, int cols) throws IOException {
        List<File> splitChildFiles = new ArrayList<>();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(fileImage);
            BufferedImage image = ImageIO.read(fis);
            // 分割成 rows*cols 个小图
            int chunks = rows * cols;
            // 计算每个小图的宽度和高度
            int chunkWidth = image.getWidth() / cols;
            int chunkHeight = image.getHeight() / rows;
            //大图中的一部分
            int count = 0;
            BufferedImage imgs[] = new BufferedImage[chunks];
            for (int x = 0; x < rows; x++) {
                for (int y = 0; y < cols; y++) {
                    //设置小图的大小和类型
                    imgs[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType());
                    //写入图像内容
                    Graphics2D gr = imgs[count++].createGraphics();
                    gr.drawImage(image, 0, 0, chunkWidth, chunkHeight, chunkWidth * y, chunkHeight * x, chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, null);
                    gr.dispose();
                }
            }
            // 输出小图
            String suffix = FileUtil.getSuffix(fileImage);
            String prefix = FileUtil.getPrefix(fileImage);
            for (int i = 0; i < imgs.length; i++) {
                File splitChildFiled = new File(fileImage.getParent(), prefix + "_" + i + "." + suffix);
                ImageIO.write(imgs[i], suffix, splitChildFiled);
                splitChildFiles.add(splitChildFiled);
            }
        } finally {
            if (Objects.nonNull(fis)) {
                fis.close();
            }
        }
        return splitChildFiles;
    }
}
